var prefix = jsctx + "/invoiceApply";

var invoiceApply = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });
    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listPageInvoiceApply",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    pageList: [10, 20, 30],
                    pageSize: 10,
                    pageNumber: 1,
                    sidePagination: "server",
                    cache: false,
                    // height: h,
                    paginationShowPageGo: true,
                    rightFixedColumns: false,
                    // showColumns: true,
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            addressee: $("#addressee").val().trim(),
                            orderNum: $("#orderNum").val().trim(),
                            beginTime: $("#beginTime").val().trim(),
                            endTime: $("#endTime").val().trim()
                        };
                    },
                    columns: [
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'invoiceApplyId', title: 'ID', align: 'left', width: '100'},
                        {
                            field: 'invoiceNormalType', title: '开票类型',
                            width: '100', align: 'left',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '个人开票'
                                } else if (value == '1') {
                                    return '企业开票'
                                }
                            }
                        },
                        {field: 'addressee', title: '申请人', width: '100', align: 'left'},
                        {field: 'createdTime', title: '申请时间', width: '100', align: 'left'},
                        {field: 'invoiceTitle', title: '开票主体', width: '100', align: 'left'},
                        {
                            field: 'companyCredit', title: '税号', width: '100', align: 'left',
                            formatter: function (value, row, index) {
                                if (row.invoiceNormalType == '0') {
                                    return '-'
                                } else if (row.invoiceNormalType == '1') {
                                    return value
                                }
                            }
                        },
                        {field: 'orderNum', title: '订单号', width: '100', align: 'left'},
                        {field: 'amount', title: '开票金额', width: '100', align: 'left'},
                        {
                            field: 'status', title: '状态', width: '100', align: 'left',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '未审核'
                                } else if (value == '1') {
                                    return '已通过'
                                } else if (value == '2') {
                                    return '不通过'
                                }
                            }
                        },
                        {field: 'lastUpdatedTime', title: '操作时间', width: '100', align: 'left'},
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '200',
                            align: 'center',
                            class: 'operate-td',
                            formatter: function (value, row, index) {
                                var a = '';
                                var b = '';
                                var c = '';
                                var d = '';
                                a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="详情" onclick="invoiceApply.detail(\''
                                    + row.invoiceApplyId + '\')">详情</a> ';
                                if (userInfo == "0") {
                                    c = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="通过" onclick="invoiceApply.pass(\''
                                        + row.invoiceApplyId + '\')">通过</a> ';
                                    d = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="驳回" onclick="invoiceApply.overrule(\''
                                        + row.invoiceApplyId + '\')">驳回</a> ';
                                }
                                // if (OperationsManagement_invoiceApply_export) {
                                    b = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="导出" onclick="invoiceApply.exportInvoiceOrder(\''
                                        + row.invoiceApplyId + '\')">导出</a> ';
                                // }



                                if (row.status == '0') {
                                    return a + c + d;
                                } else {
                                    return a;
                                }


                            }
                        }
                    ]
                });
    }

    function reLoad() {
        $(".fixed-table-header-columns").css("display", "none");
        $(".fixed-table-body-columns").css("display", "none");
        $('#exampleTable').bootstrapTable('refresh');
    }

    function browse(value) {
        var uploadPath = $("#uploadPath").val();
        var url = uploadPath + value
        var img_infor = '<img src= "' + url + '" height="100%" width="100%" />';
        layer.open({
            type: 1,
            title: '浏览',
            maxmin: true,
            shadeClose: true, //点击遮罩关闭层
            area: ['70%', '90%'],
            content: img_infor
        });
    }

    function pass(invoiceApplyId) {
        layer.confirm('确定要通过？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/review",
                type: "post",
                data: {
                    'invoiceApplyId': invoiceApplyId,
                    'status': '1'

                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function overrule(invoiceApplyId) {
        layer.confirm('确定要驳回？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/review",
                type: "post",
                data: {
                    'invoiceApplyId': invoiceApplyId,
                    'status': '2'
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function exportInvoiceApply() {
        $.fileDownload(prefix + "/exportInvoiceApply", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                addressee: $("#addressee").val().trim(),
                orderNum: $("#orderNum").val().trim(),
                beginTime: $("#beginTime").val().trim(),
                endTime: $("#endTime").val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    function exportInvoiceOrder(invoiceApplyId) {
        location.href = prefix + "/exportInvoiceOrder?invoiceApplyId=" + invoiceApplyId;
    }

    function editInvoiceApply(invoiceApplyId) {
        location.href = prefix + "/editInvoiceApply/" + invoiceApplyId;
    }

    function detail(id) {
        location.href = prefix + "/detail/" + id;
    }


    function goBack() {
        window.history.back();
    }

    function add() {
        location.href = prefix + "/add";
    }

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                addressee: $('#addressee').val().trim(),
                orderNum: $('#orderNum').val().trim(),
                beginTime: $('#beginTime').val().trim(),
                endTime: $('#endTime').val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }


    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        exportInvoiceApply: exportInvoiceApply,
        exportInvoiceOrder: exportInvoiceOrder,
        exportList: exportList,
        editInvoiceApply: editInvoiceApply,
        pass: pass,
        overrule: overrule,
        browse: browse,
        detail:detail,
        add: add,
    }

})();

var detailInvoiceApply = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listOrderWithInvocieApply",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    queryParams: function (params) {
                        return {
                            invoiceApplyId: $("#invoiceApplyId").val()
                        };
                    },
                    columns: [
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {
                            field: 'status', title: '状态', width: '60', align: 'left',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '<span >未充电</span>'
                                } else if (value == '1') {
                                    return '<span >充电中</span>'
                                } else if (value == '2') {
                                    return '<span >完成</span>'
                                } else if (value == '3') {
                                    return '<span >充电结算中</span>'
                                }
                            }
                        },
                        {field: 'stationName', title: '站点名称', width: '120', align: 'left'},


                        {field: 'orderNum', title: '订单号', width: '130', align: 'left'},
                        // {field: 'nickname', title: '会员名', width: '80', align: 'left'},
                        {field: 'carNum', title: '车牌', width: '90', align: 'left'},

                        {field: 'startTime', title: '开始时间', width: '90', align: 'left'},
                        {field: 'endTime', title: '结束时间', width: '90', align: 'left'},
                        {field: 'lastTime', title: '充电时长', width: '80', align: 'left'},
                        // {field: 'totalPower', title: '电量<br>(度)', width: '65', align: 'right'},
                        // {field: 'totalElecMoney', title: '电费<br>(元)', width: '65', align: 'right'},
                        {field: 'totalSeviceMoney', title: '服务费<br>(元)', width: '70', align: 'right'},
                        {field: 'discountAmount', title: '优惠<br>(元)', width: '65', align: 'right'},
                        {field: 'totalMoney', title: '总价<br>(元)', width: '65', align: 'right'},
                        {field: 'payAmount', title: '实付<br>(元)', width: '65', align: 'right'},
                        {
                            title: '操作',
                            field: 'operate', width: '150', align: 'center', class: 'operate-td',
                            formatter: function (value, row, index) {
                                var a = '<a class="btn btn-success btn-sm" href="#" title="详情" onclick="detailInvoiceApply.orderContent(\''
                                    + row.orderId + '\')">详情</a> ';
                                return a;

                            }
                        }
                    ],
                });
    }

    function reLoad() {
        $(".fixed-table-header-columns").css("display", "none");
        $(".fixed-table-body-columns").css("display", "none");
        $('#exampleTable').bootstrapTable('refresh');
    }

    //订单详情
    function orderContent(orderId) {
        location.href = jsctx + "/orderInfo/orderContent/" + orderId;
    }

    return {
        init: init,
        orderContent: orderContent
    };
})();

var addInvoiceApply = (function () {
    function init() {
        validateRule();
    };

    var isajaxsend = true;

    function save() {

            var formData = $('#frm').serializeObject();
            $.ajax({
                cache: false,
                type: "POST",
                dataType: "json",
                headers:{
                    'Content-Type':'application/json;charset=UTF-8',
                },
                url: prefix + "/addInvoiceApply",
                data: JSON.stringify({
                    "invoiceApply":formData,
                    "orderNum":$("#orderNum").val(),
                }),
                processData: false,
                contentType: false,
                async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        isajaxsend = false;
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        isajaxsend = true;
                        parent.layer.alert(data.message)
                    }

                }
            });

    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                pileNo: {
                    required: true
                },
                pileName: {
                    required: true
                }

            },
            messages: {
                pileNo: {
                    required: icon + "请输入桩群编号"
                },
                pileName: {
                    required: icon + "请输入桩群名称"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    return {
        init: init
    };
})();
